﻿using System.Threading.Tasks;
using System.Web.Mvc;
using ZSoftInstagram.Domain;
using ZSoftInstagram.Services.Abstraction;
using ZSoftInstagram.UI.Web.Infrastructure.AppEvents.BaseControllers;
using ZSoftInstagram.UI.Web.Infrastructure.Filters;
using ZSoftInstagram.UI.ViewModels;
using System;
using System.Collections.Generic;
using ZSoftInstagram.DataAccess;
using System.Linq;
using System.Data.Entity;

namespace ZSoftInstagram.UI.Web.Controllers
{
    public class CategoryController : EntityController<Category>
    {
        private readonly ICategoryService _service;

        public CategoryController(ICategoryService service)
        {
            this._service = service;
        }

        protected override IEntityService<Category> Service
        {
            get
            {
                return this._service;
            }
        }

        public ActionResult Clear()
        {
            var context = new ApplicationDbContext();
            var user = context.Users.Include(u => u.FollowingCategories).First(u => u.Id == CurrentUserId);
            user.FollowingCategories.Clear();
            return Content(context.SaveChanges().ToString());
        }

        [ValidateModel, HttpPost, AjaxOnly]
        public async Task<ActionResult> AddUserCategory(AddUserCategoryViewModel model)
        {
            return 
                    (await this._service.AddCategoryToFollowingsAsync(model, this.CurrentUserId))
                        .ToDbServiceResult();
        }

        [AjaxOnly, Authorize, HttpGet]
        public async Task<ActionResult> SelectCategories()
        {
            var allCategories = await this._service.GetAllCategoriesAsync();
            var userCategories = await this._service.GetUserFollowingCategories(this.CurrentUserId);
            var model = new Tuple<List<CategoryViewModel>, List<CategoryViewModel>>(allCategories, userCategories);

            return View(model);
        }

        [Authorize, HttpPost, AjaxOnly]
        public async Task<ActionResult> RemoveUserCategory(AddUserCategoryViewModel model)
        {
            return 
                (await this._service.RemoveCategoryFromFollowingsUserAsync(model, this.CurrentUserId))
                    .ToDbServiceResult();
        }

        [AjaxOnly, Authorize]
        public async Task<ActionResult> Followed()
        {
            return View(await this._service.GetUserFollowingCategories(this.CurrentUserId));
        }
    }
}